package com.situ.day34;

import org.junit.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexDemo {
    @Test
    public void test1() {
        String[] array = {"2019 5013 08", "2019-5013-08", "2019501308"};
        String regex = "(\\d{4})[-\\s]?(\\d{4})[-\\s]?(\\d{2})";
        Pattern pattern = Pattern.compile(regex);
        for (String str : array) {
            Matcher matcher = pattern.matcher(str);
            if (matcher.find()) {
                //System.out.println(matcher.group(0));
                System.out.println(matcher.group(1) + "-" + matcher.group(2) + "-" + matcher.group(3));
            }
        }
    }

    @Test
    public void testSplit2() {
        //public String[] split(String regex)
        //根据给定正则表达式的匹配拆分此字符串。
        //字符串数组，它是根据给定正则表达式的匹配拆分此字符串确定的
        String regex = "\\d+";
        String str = "dfghu2344dfhi5644ffdhfi44EHHE35fhdf1235df";
        String[] array = str.split(regex);
        for (String string : array) {
            System.out.println(string);
        }
    }

    @Test
    public void testReplace() {
        //public String replaceAll(String regex,String replacement)
        //使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
        // 数字变成：#NUMBER#
        String regex = "\\d+";
        String string = "ehrifdi3456dfhdfhoDSf223dffhfd34hi";
        String result = string.replaceAll(regex, "#NUMBER#");
        System.out.println(result);
    }
}